package aimozg.joglfw.bones;

import java.util.Iterator;
import java.util.LinkedList;

/**
* Created by IntelliJ IDEA.
* User: aimozg
* Date: 02.01.11
* Time: 18:04
*/
public class BoneAnimation {
	private LinkedList<KeyPoint> points = new LinkedList<KeyPoint>();
	private String name;
	public BoneAnimation(String name,KeyPoint... points){
		this.name = name;
		for (int i = 0; i<points.length; i++){
			if (i<points.length-1){
				points[i].setNext(points[i+1]);
			}
			this.points.add(points[i]);
		}
		calcDuration();
	}
	private double duration = -1;
	public BoneAnimation loop(){
		points.getLast().setNext(points.getFirst());
		calcDuration();
		return this;
	}
	public BoneAnimation unloop(){
		points.getLast().setNext(null);
		calcDuration();
		return this;
	}
	private BoneAnimation calcDuration(){
		double c=0;
		for(KeyPoint kp:points){
			c+=kp.duration;
		}
		duration = c;
		return this;
	}
	public void apply(Bone bone,double progress){
		if (duration >0){
			while(progress> duration){
				progress-= duration;
			}
		}
		for (Iterator<KeyPoint> I = points.iterator(); I.hasNext();){
			KeyPoint kp = I.next();
			if (progress < kp.duration){
				kp.apply(bone,progress);
				return;
			} else {
				progress -= kp.duration;
			}
		}
		points.getLast().apply(bone,progress);
	}

	public double duration() {
		return duration;
	}

	public String name() {
		return name;
	}
}
